package com.zang.tree;

import com.zang.linkedlist.ListNode;

import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 二叉树的中序遍历
 *
 * @author ZVerify
 * @since 2022/10/22 10:37
 * @see <a href="https://leetcode.cn/problems/binary-tree-inorder-traversal/">...</a>
 **/
public class 二叉树的中序遍历 {

    List<Integer> integers = new ArrayList<>();
    public List<Integer> inorderTraversal(TreeNode root) {


        if (root == null){
            return integers;
        }
        dfs(root);
        return integers;
    }
    void dfs(TreeNode root){

        if (root == null) return;

        dfs(root.left);
        integers.add(root.val);
        dfs(root.right);
    }

    // 迭代
    public List<Integer> iteration(TreeNode root) {

        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();

        TreeNode treeNode = root;
        // 如果左边有将左边所有的放入栈， 然后弹出加入list，判断是否有右节点，如果有右节点将其加入栈，接着看是否有左节点，依次循环
        while (treeNode!=null || !stack.empty()) {
            if (treeNode!=null) {
                stack.push(treeNode);
                treeNode = treeNode.left;
            }else {
                TreeNode pop = stack.pop();
                list.add(pop.val);
                treeNode = pop.right;
            }
        }

        return list;


    }
}
